package com.example.coinhelper.Fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.coinhelper.Adapter.DetailsAdapter;
import com.example.coinhelper.Adapter.TypeAdapter;
import com.example.coinhelper.Bean.Details;
import com.example.coinhelper.Bean.Type;
import com.example.coinhelper.Manage.DetailsManage;
import com.example.coinhelper.R;
import com.example.coinhelper.db.TypeDBHelper;
import com.example.coinhelper.utils.KeyBoardUtils;
import com.example.coinhelper.utils.MySesseion;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link OutcomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class OutcomeFragment extends Fragment implements View.OnClickListener{

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private DetailsManage detailsManage;
    private String mParam2;
    TextView typeTv , beizhu , timeTv;
    private Handler handler = new Handler();
    private TextView liveTimeText,liveTimeText_hh_mm;
    KeyboardView keyboardView;
    EditText moneyEt;
    ImageView typeIv;
    GridView typeGv;
    Type type;
    TypeAdapter typeAdapter;
    List<Type> typeList;
    Boolean paramBean = false;  //判断是否是值传递过来了
    Details details;
    private KeyBoardUtils keyBoardUtils;
    public OutcomeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment OutcomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static OutcomeFragment newInstance(String param1, String param2) {
        OutcomeFragment fragment = new OutcomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if(!paramBean) {
            System.out.println("参数没有传过来");
            details = new Details();
            details.setOperation("其他");
            details.setUsername(MySesseion.USER.getUsername());
            details.setIcon(R.mipmap.ic_qita_fs);
            details.setOther("");
        }
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_outcome, container, false);
        GridView TypeGridView = view.findViewById(R.id.frag_record_gv);
        TypeDBHelper typeDBHelper=new TypeDBHelper(requireContext());
         typeList =  typeDBHelper.getTypesByKind(0);
        TypeAdapter typeAdapter = new TypeAdapter(requireContext(),typeList);
        TypeGridView.setAdapter(typeAdapter);
        liveTimeText = view.findViewById(R.id.frag_record_tv_time);
        liveTimeText_hh_mm = view.findViewById(R.id.frag_record_tv_time_hhmm);
        if(!paramBean){
            updateTime();
        }

        initView(view);
        getGridViewListener();
        loadDataToGridView();
        return view;
    }
    /*获取当前时间*/


    private void updateTime() {
        // 获取当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
        SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm", Locale.getDefault());
        String currentTime = sdf.format(new Date());
        String currentTime1 = sdf1.format(new Date());

        // 更新 TextView 显示的时间
        liveTimeText.setText(currentTime);

        liveTimeText_hh_mm.setText(currentTime1);
        details.setDate(currentTime+" "+currentTime1);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null); // 停止更新时间
    }
    private void initView(View view) {
        keyboardView = (KeyboardView)(view).findViewById(R.id.frag_record_keyboard);
        moneyEt = view.findViewById(R.id.frag_record_et_money);
        typeIv = view.findViewById(R.id.frag_record_iv);
        typeGv = view.findViewById(R.id.frag_record_gv);
        typeTv = view.findViewById(R.id.frag_record_tv_type);
        beizhu = view.findViewById(R.id.frag_record_tv_beizhu);
        timeTv = view.findViewById(R.id.frag_record_tv_time);
        liveTimeText_hh_mm = view.findViewById(R.id.frag_record_tv_time_hhmm);
        beizhu.setOnClickListener(this);
        timeTv.setOnClickListener(this);
        liveTimeText_hh_mm.setOnClickListener(this);

        if(paramBean) {
            System.out.println("参数传过来了");
            typeIv.setImageResource(details.getIcon());
            typeTv.setText(details.getOperation());
            moneyEt.setText(Math.abs(details.getMoney())+"");
            moneyEt.setSelection(String.valueOf(Math.abs(details.getMoney())).length());
            beizhu.setText(details.getOther()==null?"":details.getOther());
            String text = details.getDate();
            String[] parts = text.split(" "); // 使用空格作为分隔符
            timeTv.setText(parts[0]);
            liveTimeText_hh_mm.setText(parts[1]);


        }

        // 让自定义的键盘显示出来
        keyBoardUtils = new KeyBoardUtils(keyboardView, moneyEt);
        keyBoardUtils.showKeyboard();
        // 设置接口，监听确定键盘被点击
        keyBoardUtils.setOnEnsureListener(new KeyBoardUtils.OnEnsureListener() {
            @Override
            public void onEnsure() {
                // 获取输入钱数
                String moneyStr = moneyEt.getText().toString();
                if (TextUtils.isEmpty(moneyStr) ) {
                    //getActivity().finish();
                    //这里不在默认结束本层会话，而是添加提示
                    Toast.makeText(getActivity(), "金额不能为空", Toast.LENGTH_LONG).show();
                    return;
                }else {
                    String regex = "[0]+";
                    Pattern pattern = Pattern.compile(regex);
                    Matcher matcher = pattern.matcher(moneyStr);
                    if(matcher.matches()){
                        Toast.makeText(getActivity(), "金额不能为0", Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                float money = Float.parseFloat(moneyStr);
                details.setMoney(-Math.round(money * 100.0) / 100.0);
                detailsManage = new DetailsManage(requireContext());
                if(paramBean){
                    detailsManage.updateDetails(details);
                }else{
                    saveAccountToDb();
                }
                // 获取记录的信息，插入到数据库中
                List<Details> updatedDetailsList = detailsManage.getAllDetailsByUsername(MySesseion.USER.getUsername());
                MySesseion.DETAILSADAPTER.updateDetailsList(updatedDetailsList);
                MySesseion.DETAILSADAPTER.notifyDataSetChanged();
                // 返回上一级
                getActivity().finish();
            }
        });
    }

    private void saveAccountToDb() {
        detailsManage = new DetailsManage(requireContext());
        detailsManage.addDetails(details);
        //System.out.println(details.toString());
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.frag_record_tv_time) {
            showTimeDialog();
        } else if (id == R.id.frag_record_tv_beizhu) {
            keyBoardUtils.hideKeyboard();
            showDialog();
        }else if(id==R.id.frag_record_tv_time_hhmm){
            showTimeDialog_hhmm();
        }
    }
    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("输入备注");
        // 设置备注输入框
        final EditText input = new EditText(requireContext());
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        builder.setView(input);

        // 设置确定按钮
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String userInput = input.getText().toString();
                // 在这里使用用户输入的备注（userInput）
                // 例如，将备注设置到合适的控件上
                beizhu.setText(userInput);
                details.setOther(userInput);
                keyBoardUtils.showKeyboard();
            }
        });

        // 设置取消按钮
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                keyBoardUtils.showKeyboard();
            }
        });

        // 创建并显示对话框
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    @SuppressLint("ResourceType")
    private void showTimeDialog() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog.OnDateSetListener onDateSetListener =new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                month = month+1;
                String str = year+"年"+month+"月"+day+"日";//把日期变成字符串格式显示出来
                timeTv.setText(str);//文本框显示的内容设置成经过逻辑处理后的日期
                details.setDate(str+" "+liveTimeText_hh_mm.getText());
            }
        };
        new DatePickerDialog(requireContext(),3,onDateSetListener,year,month,dayOfMonth).show();
    }
    private void showTimeDialog_hhmm() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);

        TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) {
                String timeStr = String.format(Locale.getDefault(), "%02d:%02d", hourOfDay, minute);
                // 将选定的时间显示在文本框中，或者进行其他逻辑操作
                liveTimeText_hh_mm.setText(timeStr);
                details.setDate(timeTv.getText()+" "+timeStr);
            }
        };
        new TimePickerDialog(requireContext(),3, onTimeSetListener, hour, minute, true).show();
    }
    /*获取GV的点击事件*/
    private void getGridViewListener() {
        typeGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                typeAdapter.setSelectPos(position);
                typeAdapter.notifyDataSetChanged(); //显示绘制
                type  = typeList.get(position);
                String typeName = type.getTypeName();
                typeTv.setText(typeName);
                details.setOperation(typeName);
                int sImageId = type.getsImageId();
                typeIv.setImageResource(sImageId);
                details.setIcon(sImageId);
            }
        });
    }
    public void setAccountBeanBean(Details details){
        this.details = details;
        paramBean = true;
    }

    void loadDataToGridView() {
        typeAdapter = new TypeAdapter(getContext(), typeList);
        typeGv.setAdapter(typeAdapter);
    }
}